package org.budo.redis.jdbc.driver.statement.set.sorted;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.ObjectArrayResultSet;
import org.budo.redis.jdbc.driver.BudoRedisJdbcConnection;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;
import org.budo.redis.jdbc.driver.parser.RedisSqlStatement;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;

/**
 * @author lmw
 */
public class ZADD extends AbstractRedisStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        byte[] key = this.parameter(0, preparedStatement);

        Map<byte[], Double> members = new HashMap<byte[], Double>();
        for (int i = 1; i < ((RedisSqlStatement) this.getSqlStatement()).getFunctionParameters().length; i = i + 2) { // 从第二个开始
            Double score = this.parameterNumber(i, preparedStatement).doubleValue();
            byte[] member = this.parameter(i + 1, preparedStatement);
            members.put(member, score);
        }

        RedisStatementExecutor statementExecutor = ((BudoRedisJdbcConnection) preparedStatement.getConnection()).getStatementExecutor();
        Long zadd = statementExecutor.zadd(key, members);

        ResultSet resultSet = new ObjectArrayResultSet(new String[] { "zadd" }, new Object[] { zadd });
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}